<?php

    namespace yaliSDK\live;

    use think\Exception;
    use yaliSDK\common\BaseRepository;
    use yaliSDK\common\Constrants;
    use yaliSDK\common\IRepository;

    class AnchorRepository extends BaseRepository implements IRepository {
        private static $TABLE = 'anchor';

        function save($data, $option = []): bool {

            return $this->db->name(self::$TABLE)->insert($data) > 0;
        }

        function get($id, $option = []) {
            $anchor = null;
            try {
                $option['id'] = $id;
                $option['isDetail'] = true;
                $result = $this->lists($option);
                if (!empty($result) && !empty($result['list']) && !empty($result['list'][0])) {
                    $anchor = $result['list'][0];
                }
            } catch (Exception $e) {

            }
            return $anchor;

        }

        function lists($option = []) {
            $result = null;
            try {
                $domain = $option['domain'] ?? null;// 域名
                $web_id = $this->getWebIdByDomain($domain);//站点
                $uid = $option['uid'] ?? null;// 访问用户uid
                $isDetail = $option['isDetail'] ?? null;
                $isLive = $option['isLive'] ?? null;
                // 获取正在直播中的
                if ($isLive) {
                    $cb = function () use ($option, $web_id, $uid) {
                        $keywords = $option['keywords'] ?? '';

                        $id = $option['id'] ?? null;

                        $key = $option['key'] ?? 'id';
                        // 第一个子查询
                        $sub1 = $this->db
                            ->name(self::$TABLE)
                            ->alias('a')
                            ->join('live l', 'l.anchor_id = a.id')
                            ->whereNotNull('l.current_id')
                            ->where(['l.status' => Constrants::$LIVE_START]);

                        if ($web_id) {
                            $sub1->where(['l.web_id' => $web_id]);
                        }
                        // 第二个子查询
                        $sub2 = $this->db
                            ->name(self::$TABLE)
                            ->alias('a')
                            ->join('live l', 'l.anchor_id = a.id')
                            ->where(['l.status' => Constrants::$LIVE_START]);
                        if ($web_id) {
                            $sub2->where(['l.web_id' => $web_id]);
                        }

                        $sub1 = $sub1->field('a.id, count(l.id) as total')
                            ->group('a.id')->buildSql();

                        $sub2 = $sub2->field('a.id, count(l.id) as total')
                            ->group('a.id')->buildSql();
                        $query = $this->db->table('yali_anchor a')
                            ->join($sub1 . ' d', 'a.id=d.id', 'left')
                            ->join($sub2 . ' g', 'a.id=g.id', 'left');

                        if (!empty($keywords)) {
                            $query->where(['a.name' => ['like', '%' . $keywords . '%']]);
                        }

                        if ($id) {
                            $query->where(['a.' . $key => $id]);
                        }
                        $query->field('a.*, d.total as total_playing, g.total as total_start')
                            ->order('d.total desc, g.total desc');
                        return $query;
                    };
                } else {
                    $cb = function () use ($option, $web_id, $uid) {
                        $keywords = $option['keywords'] ?? '';

                        $id = $option['id'] ?? null;
                        $isFollow = $option['isFollow'] ?? null;


                        $key = $option['key'] ?? 'id';
                        $query = $this->db
                            ->name(self::$TABLE)
                            ->alias('l');
                        if (!empty($keywords)) {
                            $query->where(['l.name' => ['like', '%' . $keywords . '%']]);
                        }

                        if ($id) {
                            $query->where(['l.' . $key => $id]);
                        }

                        $query->field('l.*');
                        if ($web_id) {
                            if ($isFollow && !is_null($uid)) {

                                // 是否获取我关注的主播
                                if ($isFollow) {
                                    $query->join('live_follow f', 'f.anchor_id = l.id', 'left');
                                    $query->where(['f.web_id' => $web_id, 'f.uid' => $uid]);
                                }
                            }
                        }
                        //$query->order('addtime desc');
                        return $query;
                    };
                }


                // 计算总量
                $totalcb = function ($anchorId, $joinTable, $isUser) use ($web_id, $uid) {
                    $con = '';
                    if ($isUser === true && !is_null($web_id) && !is_null($uid)) {
                        $con = ' and z.uid = ' . $uid . ' and z.web_id = ' . $web_id;
                    }
                    $result = $this->db
                        ->name(self::$TABLE)
                        ->alias('l')
                        ->join($joinTable . ' z', 'z.anchor_id = l.id' . $con, 'left')
                        ->where(['l.id' => $anchorId])
                        ->field('count(z.id) as total')->group('l.id')->find();
                    if (empty($result) || empty($result['total'])) {
                        return 0;
                    }
                    return $result['total'];
                };
                $total = $cb()->count();// 当前总数
                $isCount = $option['isCount'] ?? false;
                if (empty($isCount)) {
                    $page = $option['page'] ?? 1;
                    $limit = $option['rows'] ?? 20;
                    $list = $cb()->page($page, $limit)->select();
                    if ($isDetail && is_array($list)) {
                        $list = array_map(function ($item) use ($totalcb) {
                            // 获取总活动赞数
                            $total_zan = $totalcb($item['id'], 'live_zan', false);
                            $item['total_live_zan'] =$total_zan;
                            // 获取总关注
                            $total_follow = $totalcb($item['id'], 'live_follow', false);
                            $item['total_follow'] =$total_follow;
                            // 获取个人用户是否关注
                            $is_follow = $totalcb($item['id'], 'live_follow', true);
                            $item['is_follow'] = $is_follow;
                            $item['total_live'] = $totalcb($item['id'], 'live', false);

                            return $item;

                        }, $list);
                    }
                }
                if (!empty($result) && !empty($result[0]) && empty($result[0]['id'])) {
                    $list = [];
                }
                return [
                    'list' => $list,
                    'total' => $total,
                ];
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }
        }

        function update($data, $option = []): bool {
            $liveId = null;
            try {
                $liveId = $this->db->name(self::$TABLE)->update($data);

            } catch (Exception $e) {

            }
            return $liveId === 1;
        }

        function isExist($id, $option): bool {
            $key = $option['key'] ?? 'id';
            return $this->db->name(self::$TABLE)->where([$key => $id])->count('id') > 0;
        }
    }
